package logger

import (
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

const logDir = "./logs"

var Logger *zap.Logger

func InitLogger() {
	_ = os.MkdirAll(logDir, os.ModePerm)

	// 编码配置
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:       "time",
		LevelKey:      "level",
		NameKey:       "logger",
		CallerKey:     "caller",
		MessageKey:    "msg",
		StacktraceKey: "stack",
		LineEnding:    zapcore.DefaultLineEnding,
		EncodeLevel:   zapcore.CapitalLevelEncoder,
		EncodeTime:    zapcore.ISO8601TimeEncoder,
		EncodeCaller:  zapcore.ShortCallerEncoder,
	}
	// 输出编码格式（JSON 格式更适合日志收集）
	encoder := zapcore.NewJSONEncoder(encoderConfig)

	// 不同等级的日志文件
	infoWriter := getLogWriter(logDir + "/info.log")
	warnWriter := getLogWriter(logDir + "/warn.log")
	errorWriter := getLogWriter(logDir + "/error.log")

	// 分别定义不同日志级别的 Core
	infoCore := zapcore.NewCore(encoder, zapcore.AddSync(infoWriter), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl >= zapcore.InfoLevel && lvl < zapcore.WarnLevel
	}))

	warnCore := zapcore.NewCore(encoder, zapcore.AddSync(warnWriter), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl >= zapcore.WarnLevel && lvl < zapcore.ErrorLevel
	}))

	errorCore := zapcore.NewCore(encoder, zapcore.AddSync(errorWriter), zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
		return lvl >= zapcore.ErrorLevel
	}))

	// 将所有 core 合并
	core := zapcore.NewTee(infoCore, warnCore, errorCore)

	// 创建 logger
	logger := zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))
	Logger = logger
}

// Lumberjack 日志切割配置
func getLogWriter(filename string) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    50,   // 每个日志文件最大 50MB
		MaxBackups: 10,   // 保留最多 10 个备份
		MaxAge:     30,   // 保留 30 天
		Compress:   true, // 是否压缩归档
	}
	return zapcore.AddSync(lumberJackLogger)
}
